import { ipcMain } from 'electron';

import api from './api';

ipcMain.on('get-token', async (event, arg) => {
  try {
    let data = await api.getAccessToken(arg.code, arg.config.APPID, arg.config.APPKEY, arg.config.REDIRECT_URI);
    event.sender.send('token-back', data);
  } catch (error) {
    event.sender.send('token-back', {
      errmsg: error,
      code: 1
    });
  }
});

ipcMain.on('refresh-token', async (event, arg) => {
  try {
    let data = await api.refreshToken(arg.id, arg.key, arg.refresh_token);
    event.sender.send('token-back', data);
  } catch (error) {
    event.sender.send('token-back', {
      errmsg: error,
      code: 1
    });
  }
})

ipcMain.on('get-list', async (event, arg) => {
  let data;
  try {
    if (arg.folderid) {
      data = await api.getFileList(arg.access_token, arg.folderid, arg.startNumber, arg.endNumber);
      event.sender.send('list-back', data);
    } else {
      // 云盘id
      let mydiskID = '';
      data = await api.getFileList(arg.access_token);
      if (data.result['$'].resultCode == '0') {
        let mydisk = data.result.getDiskResult["0"].catalogList["0"].catalogInfo;
        for (let i in mydisk) {
          if (mydisk[i].catalogName["0"] == '我的文件夹') {
            mydiskID = mydisk[i].catalogID["0"];
            break;
          }
        }
        let data2 = await api.getFileList(arg.access_token, mydiskID);
        event.sender.send('list-back', data2, mydiskID);
      } else {
        event.sender.send('list-back', data);
      }
    }
  } catch (error) {
    event.sender.send('list-back', {
      errmsg: error,
      code: 1
    });
  }
})

ipcMain.on('get-download', async (event, arg) => {
  try {
    let data = await api.getDownload(arg.access_token, arg.fileid, arg.phone);
    event.sender.send('download-back', data);
  } catch (error) {
    event.sender.send('download-back', {
      errmsg: error,
      code: 1
    });
  }
})

ipcMain.on('delete-file', async (event, arg) => {
  try {
    let data = await api.deleteFile(arg.access_token, arg.filelist);
    event.sender.send('delete-back', data);
  } catch (error) {
    event.sender.send('delete-back', {
      errmsg: error,
      code: 1
    });
  }
})

ipcMain.on('delete-allupload', async (event, arg) => {
  try {
    let data = await api.deleteFile(arg.access_token, arg.uploadTaskID, arg.fileName);
    event.sender.send('deleteAllUpload-back', data);
  } catch (error) {
    event.sender.send('deleteAllUpload-back', {
      errmsg: error,
      code: 1
    });
  }
})

ipcMain.on('get-uploadUrl', async (event, arg) => {
  try {
    let data = await api.getUploadFileUrl(arg.access_token, arg);
    event.sender.send('uploadUrl-back', data, arg.pos);
  } catch (error) {
    event.sender.send('uploadUrl-back', {
      errmsg: error,
      code: 1
    });
  }
});
